define(['app'], function(app) {
	'use strict';

	var controller = function controller($scope, Myagent_add, Auth, GoDialog, GoAddress, GoCatTypeAuth, $ionicModal, $window, $stateParams, $timeout, GoPage, $ionicScrollDelegate) {
		
		//数据模型
		$scope.input = new Object();
		function initInput(){
//			$scope.cats = new Array(); //显示的类目，不提交
			$scope.regions = new Array(); //显示的地区，不提交
			$scope.input.id = "";//提交，店铺ID/编辑id
			$scope.agentName = "";//显示，代理商店铺名
			$scope.input.credit_line = 0;//授信额度，默认为0
			$scope.input.brand = {};//品牌
			$scope.input.cat_type = new Array(); //提交，格式AAA/BBB/CCC:CCC的id（最后一级的id）
			$scope.input.region = new Array(); //提交，格式AAA/BBB/CCC:CCC的id（最后一级的id）
			$scope.input.key = "";//搜索授权中心
			$scope.input.brandArr = new Array({});//提交，存放品牌id、分类id、地区id
			$scope.input.brandArr[0].cat_type = new Array();
			$scope.brandArrShow = new Array({});//显示，存放品牌id、分类id、地区id
			$scope.brandArrShow[0].cats = new Array();
			if($stateParams.store_id){
				$scope.input.id = $stateParams.store_id;
			}
			$scope.title = $stateParams.store_id?'编辑':"添加";
			$scope.title2 = $stateParams.isAgent=='false'?"加盟店":"授权中心";
		}
		
		$scope.initialize = function(){//每次添加完地区/分类都要初始化这3个参数，所以把他们单独放在函数里
			$scope.input.cat1 = {id:0,name:"请选择大分类"};
			$scope.input.cat2 = {id:0,name:"请选择中分类"};
			$scope.input.cat3 = {id:0,name:"请选择小分类"};
			$scope.input.province = {id:0,name:"请选择省份"}; //省市区三级联动
			$scope.input.city = {id:0,name:"请选择城市"}; //省市区三级联动
			$scope.input.district = {id:0,name:"请选择区/县"}; //省市区三级联动
        }
		
		$scope.$on('$ionicView.afterEnter', function() {
//			var lan = 0; //这是状态栏，只有ios的APP才有
//			if(window.cordova && window.cordova.plugins && ionic.Platform.isIOS()) {
//				lan = 20;
//			}
//			var all = window.innerHeight;
//			$scope.myObj = {
//				"height": all - 44 - 60 - lan + "px"
//			}
			initInput();
			$scope.initialize();
			$scope.init_data();
		}, false);
		
		//初始化
		$scope.init_data = function(){
			//代理商一览
			$scope.doSearchAgent();
			//详情
			if($scope.input.id){
				Myagent_add.agenter_detail($scope.input.id,function(data){
					$scope.scope = data.brand;//控制地区、品牌块的删除按钮的显示隐藏
					console.log($scope.scope)
					$scope.agentName = data.store_name;
//					$scope.input.id = data.store_id;
					$scope.input.credit_line = parseFloat(data.credit_line);
					if(!data.brand||data.brand.length==0) return;
					for (var m=0;m<data.brand[0].region.length;m++) {//地区，取data中的一个即可，因为没个品牌块的地区都是一样的
						var region = data.brand[0].region[m];
						$scope.regions.push(region.name);
						$scope.input.region.push(region.id);
					}
					for (var i=0;i<data.brand.length;i++) {//品牌
						var d = data.brand[i];
						var obj = {};//提交
						obj.id = d.id;
						obj.cat_type = new Array();
						var objShow = {};//显示
						objShow.brand = new Object();
						objShow.cats = new Array();
						objShow.is_price = d.is_price;
						objShow.brand.name = d.name;
						for (var j=0;j<d.cat_type.length;j++) {//分类
							obj.cat_type.push(d.cat_type[j].id);
							objShow.cats.push(d.cat_type[j].name);
						}
						$scope.input.brandArr[i] = obj;
						$scope.brandArrShow[i] = objShow;
					}
				})
			}
		}
		
		//搜索代理商
		$scope.doSearchAgent = function(){
			Myagent_add.agenter_list($scope.input.key, 1, function(data) {
				$scope.agenter_list = data;
			})
		}
		
		//下拉侦听，目前只能省市区三级联动
		$scope.listen_province = function (data) {
			$scope.input.city = {id:0,name:"请选择城市"}; //省市区三级联动
			$scope.input.district = {id:0,name:"请选择区/县"}; //省市区三级联动
			$scope.district_items = null;
		};
		$scope.listen_city = function (data) {
			$scope.input.district = {id:0,name:"请选择区/县"}; //省市区三级联动
		};
		//定义绑定
		var items = new Array();
		var obj1 = { name: 'input.province' };
		var obj2 = { name: 'input.city' };
		var obj3 = { name: 'input.district' };
		items.push(obj1);
		items.push(obj2);
		items.push(obj3);
		GoAddress.init_load($scope, items);
		
		$scope.doSelectProvince = function(){
			//id是值 name是显示
			GoDialog.showSelect("请选择省份",$scope.province_items,$scope.input.province,function(data){
				$scope.input.province = data;
			});
		}
		$scope.doSelectCity = function(){
			//id是值 name是显示
			GoDialog.showSelect("请选择城市",$scope.city_items,$scope.input.city,function(data){
				$scope.input.city = data;
			});
		}
		$scope.doSelectDistrict = function(){
			//id是值 name是显示
			GoDialog.showSelect("请选择区/县",$scope.district_items,$scope.input.district,function(data){
				$scope.input.district = data;
			});
		}
		$scope.doSelectCat1 = function(){
			//id是值 name是显示
			GoDialog.showSelect("大分类",$scope.cat1_items,$scope.input.cat1,function(data){
				$scope.input.cat1 = data;
			});
		}
		$scope.doSelectCat2 = function(){
			//id是值 name是显示
			GoDialog.showSelect("中分类",$scope.cat2_items,$scope.input.cat2,function(data){
				$scope.input.cat2 = data;
			});
		}
		$scope.doSelectCat3 = function(){
			//id是值 name是显示
			GoDialog.showSelect("小分类",$scope.cat3_items,$scope.input.cat3,function(data){
				$scope.input.cat3 = data;
			});
		}
		/*********************分类三级联动*****************/
		//监听品牌，获取一级分类
		$scope.$watch("input.brand",function(newVal){
			$scope.cat1_items = new Array();//一级
			$scope.cat2_items = new Array();//二级
			$scope.cat3_items = new Array();//三级
			if(newVal){
				var cat_id = "";
				$scope.brand_id = newVal.id;//一级监听、二级监听会用到
				$scope.store_id = newVal.store_id;//一级监听、二级监听会用到
				$scope.getCatList($scope.cat1_items,cat_id,$scope.brand_id,$scope.store_id);
			}
		})
		//监听一级分类，获取二级分类
		$scope.$watch("input.cat1",function(newVal){
			$scope.cat2_items = new Array();//二级
			$scope.cat3_items = new Array();//三级
			if(newVal){
				var cat_id = newVal.id;
				$scope.getCatList($scope.cat2_items,cat_id,$scope.brand_id,$scope.store_id);
			}
		})
		//监听二级分类，获取三级分类
		$scope.$watch("input.cat2",function(newVal){
			$scope.cat3_items = new Array();//三级
			if(newVal){
				var cat_id = newVal.id;
				$scope.getCatList($scope.cat3_items,cat_id,$scope.brand_id,$scope.store_id);
			}
		})
		
		//组装一级、二级、三级分类
		$scope.getCatList = function(name,cat_id,brand_id,store_id){
			Myagent_add.getCatList(cat_id,brand_id,store_id,function(data){
				for (var i=0;i<data.result.list.length;i++) {//将数组转换为对象
					var obj = new Object();
					obj.id = data.result.list[i][0];
					obj.name = data.result.list[i][1];
					name.push(obj)
				}
			})
		}
		/*********************分类三级联动*****************/
		
		/**********************品类、地区处理********************/
		//控制下拉框的显示--区域
        $scope.showSelectRegion = function(){
        	$scope.isShowSelectRegion = !$scope.isShowSelectRegion;
        }
		//控制下拉框的显示--分类
        $scope.showSelectCat = function(index){
        	var data = $scope.brandArrShow[index];
        	data.isShowSelectCat = !data.isShowSelectCat;
        }
        
        //得到要操作brandArr的索引
		$scope.getBrandArrIndex = function(index){
			$scope.brandArrIndex = index;
			$scope.input.brand = $scope.brandArrShow[$scope.brandArrIndex].brand;
		}
        
        //判断是否有空的BrandDiv存在。如果有空的存在，则不给添加。提交前也会做此判断
        function checkBrandDiv(){
        	var data = $scope.input.brandArr;
        	for (var i=0;i<data.length;i++) {
        		if(!data[i].id||data[i].cat_type.length==0){
	        		GoDialog.toast("请先完善信息，再添加！");
	        		return true;
	        		break
	        	}
        	}
        	return false;
        }
        
     	//添加品牌块
        $scope.addBrandDiv = function(){
			if(checkBrandDiv()) return;//如果有空的存在，则不给添加
        	var obj = new Object();
        	$scope.brandArrShow.push({});//元素必须为obj
        	$scope.input.brandArr.push({});//元素必须为obj
        	var index = $scope.input.brandArr.length - 1;
        	$scope.brandArrShow[index].cats = new Array();
        	$scope.input.brandArr[index].cat_type = new Array();
//      	console.log($scope.brandArrShow)
//      	console.log($scope.input.brandArr)
        }
        
        //删除品牌块
        $scope.delBrandDiv = function(index){//不能用$scope.brandArrIndex，因为$scope.brandArrIndex没有及时赋值
//      	if($scope.input.id&&index<$scope.scope.length) return;//不是必须的
        	$scope.brandArrShow.splice(index,1);
        	$scope.input.brandArr.splice(index,1);
        }
        
		//添加分类
		$scope.add_type = function() {
			$scope.cat_id = "";
			$scope.cat_name = "";
      		if($scope.input.cat3!=null && $scope.input.cat3.id !=0){
        		$scope.cat_name=$scope.input.cat1.name+"/"+$scope.input.cat2.name+"/"+$scope.input.cat3.name;
        		$scope.cat_id=$scope.cat_name+":"+$scope.input.cat3.id;
        	}else if($scope.input.cat2!=null && $scope.input.cat2.id !=0){
        		$scope.cat_name=$scope.input.cat1.name+"/"+$scope.input.cat2.name;
        		$scope.cat_id=$scope.cat_name+":"+$scope.input.cat2.id;
        	}else if($scope.input.cat1!=null && $scope.input.cat1.id !=0){
        		$scope.cat_name=$scope.input.cat1.name;
        		$scope.cat_id=$scope.cat_name+":"+$scope.input.cat1.id;
        	}
        	if($scope.cat_id&&$scope.cat_name){
        		if($scope.check($scope.cat_name,1)){//判断是否已经添加过
					$scope.brandArrShow[$scope.brandArrIndex].cats.push($scope.cat_name);
					$scope.input.brandArr[$scope.brandArrIndex].cat_type.push($scope.cat_id);
	        		$scope.initialize();//初始化分类3个modal
	        		$scope.showSelectCat($scope.brandArrIndex);//添加完，关闭弹窗
        		}else{
        			GoDialog.toast("已存在该品类！");
        		}
        	}else{
        		GoDialog.toast("请选择品类！");
        	}
		};
		
		//添加地区
		$scope.add_region = function() {
			$scope.region_id = "";
			$scope.region_name = "";
			if($scope.input.district!=null && $scope.input.district.id !=0){
        		$scope.region_name=$scope.input.province.name+"/"+$scope.input.city.name+"/"+$scope.input.district.name;
        		$scope.region_id=$scope.region_name+":"+$scope.input.district.id;
        	}else if($scope.input.city!=null && $scope.input.city.id !=0){
        		$scope.region_name=$scope.input.province.name+"/"+$scope.input.city.name;
        		$scope.region_id=$scope.region_name+":"+$scope.input.city.id;
        	}else if($scope.input.province!=null && $scope.input.province.id !=0){
        		$scope.region_name=$scope.input.province.name;
        		$scope.region_id=$scope.region_name+":"+$scope.input.province.id;
        	}
        	if($scope.region_id&&$scope.region_name){
        		if($scope.check($scope.region_name,2)){
        			$scope.regions.push($scope.region_name);
        			$scope.input.region.push($scope.region_id);
        			$scope.initialize();//初始化分类3个modal
        			$scope.showSelectRegion();//添加完，关闭弹窗
        		}else{
        			GoDialog.toast("已存在该地区！");
        		}
        	}else{
        		GoDialog.toast("请选择地区！");
        	}
		};
		//判断分类/区域的存在性
		$scope.check = function(names, type) {
			if(type == 1) {
				var data = $scope.brandArrShow[$scope.brandArrIndex].cats;
				for(var i = 0; i < data.length; i++) {
					if(data[i] == names){return false;}
				}
			} else {
				for(var i = 0; i < $scope.regions.length; i++) {
					if($scope.regions[i] == names){
						return false;
					}
				}
			}
			return true;
		}
		
		//删除分类
		$scope.delete_cat = function(parentIndex,index) {//不能用$scope.brandArrIndex
			$scope.brandArrShow[parentIndex].cats.splice(index, 1);
			$scope.input.brandArr[parentIndex].cat_type.splice(index, 1);
		}
		//删除地区
		$scope.delete_region = function(val){
			$scope.regions.splice(val, 1);
			$scope.input.region.splice(val, 1);
		}
		/**********************品类、地区处理********************/
		
		/***********品牌按字母排序************/
		//搜索品牌
		$scope.doSearchBrand = function(){
			GoCatTypeAuth.init_brandsOrderBy($scope,$scope.input.search_words_brand,Auth.get_store_id());
		}
		$scope.doSearchBrand();//初始化品牌
		//选择搜索出的结果
		$scope.getSearchBrands = function(index,secondIndex){
			$scope.closebrandOrderBy();
			$scope.input.brand = $scope.brandsOrderBy[index].brands[secondIndex];
			$scope.brandArrShow[$scope.brandArrIndex].brand =  $scope.input.brand;
			$scope.input.brandArr[$scope.brandArrIndex].id =  $scope.input.brand.id;
			//重新选择品牌，以下2个必须清空之前添加好的品类
			$scope.brandArrShow[$scope.brandArrIndex].cats = new Array(); //显示的类目，不提交
			$scope.input.brandArr[$scope.brandArrIndex].cat_type = new Array(); //提交
		}
		
		$ionicModal.fromTemplateUrl("templates/modal/brandsOrderBy.html", {
			scope: $scope,
			animation: "slide-in-up"
		}).then(function(modal) {
			$scope.modal_brandOrderBy = modal;
		});
		//打开
		$scope.openbrandOrderBy = function(index) {
			if($scope.input.id&&index<$scope.scope.length) return;//编辑不能重新选择品牌
			$scope.modal_brandOrderBy.show();
		}
		//隐藏
		$scope.closebrandOrderBy = function() {
			$scope.modal_brandOrderBy.hide();
		}
		//定位到指定位置
		$scope.goToLetter = function($event,letter){
			$event.stopPropagation();//阻止事件冒泡
			$scope.currentLetter = letter;
			var height = document.getElementById(letter).offsetTop;//离顶部的距离
		 	$ionicScrollDelegate.$getByHandle("allBrands").scrollTo(0,height);
		}
		/***********品牌按字母排序************/
		
		/***********选择授权中心************/
		$ionicModal.fromTemplateUrl("templates/modal/select_agent.html", {
			scope: $scope,
			animation: "slide-in-up"
		}).then(function(modal) {
			$scope.modal_agent = modal;
		});
		//打开
		$scope.openAgentModal = function() {
			if($scope.store_id) return;//编辑不能重新选择店铺
			$scope.modal_agent.show();
		}
		//隐藏
		$scope.closeAgentModal = function() {
			$scope.modal_agent.hide();
		}
		$scope.getAgent = function(index){
			$scope.closeAgentModal();
			var agent = $scope.agenter_list.store[index];
			$scope.input.id = agent.store_id ;
			$scope.agentName = agent.store_name ;
		}
		/***********选择授权中心************/
		
		//提交
		$scope.submit = function() {
			if(!$scope.input.id) {
				GoDialog.toast("请选择授权中心");
				return;
			}
			if(!$scope.input.credit_line){
				GoDialog.toast("请输入授权额度");
				return;
			}
			if($scope.input.region.length==0){
				GoDialog.toast("请选择地区");
				return;
			}
			if(checkBrandDiv()){
				GoDialog.toast("请完善品牌、分类信息");
				return;
			}
			//把$scope.input.region和$scope.brandArrShow的is_price赋给$scope.input.brandArr
			var brandArr = $scope.input.brandArr;
			var brandArrShow = $scope.brandArrShow;
			for (var i=0;i<brandArr.length;i++) {
				brandArr[i].is_price = brandArrShow[i].is_price?brandArrShow[i].is_price:false;
				brandArr[i].region = $scope.input.region;
			}
			
			var params = new Object();
			params.id = $scope.input.id;//代理商店铺ID
			params.credit_line = $scope.input.credit_line;
			params.brand = $scope.input.brandArr;
			params = JSON.stringify(params);
			Myagent_add.agent_add(params, function(data) {
				if(data.success) {
					GoDialog.toast("提交成功");
					GoPage.go_states("myagent");
				} else{
					GoDialog.alert("提示",data.msg);
				}
			});
		}
		
		/*****************上下拉刷新******************/
		$scope.isLoad = false;
		$scope.nPage = 1;
		$scope.doRefresh = function() {
			$scope.isLoad = true;
			Myagent_add.agenter_list($scope.input.key, 1, function(data) {
				$scope.agenter_list = data;
				$scope.nPage = 1;
			}, function() {
				$scope.$broadcast('scroll.refreshComplete');
				$timeout(function() {
					$scope.isLoad = false;
				}, 1500);
			})
		};
		$scope.doRefreshMore = function() {
			$scope.isLoad = true;
			Myagent_add.agenter_list($scope.input.key, $scope.nPage + 1, function(data) {
				if(data != null) {
					if($scope.agenter_list.store != undefined) {
						$scope.agenter_list.store = $scope.agenter_list.store.concat(data.store);
						$scope.nPage += 1;
					} else {
						$scope.agenter_list = data;
					}
				}
			}, function() {
				$scope.$broadcast('scroll.infiniteScrollComplete');
				$timeout(function() {
					$scope.isLoad = false;
				}, 1500);
			})
		};
		/*****************上下拉刷新******************/
		
		
	}

	controller.$inject = ['$scope', 'Myagent_add', 'Auth', 'GoDialog', 'GoAddress', 'GoCatTypeAuth', '$ionicModal', '$window', '$stateParams', '$timeout', 'GoPage','$ionicScrollDelegate'];

	return app.registerController("myagent_addctrl", controller);
});